package cn.stylefeng.roses.kernel.oauth2.modular.controller;

import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.oauth2.api.pojo.OAuth2Config;
import cn.stylefeng.roses.kernel.oauth2.modular.factory.OAuthRequestFactory;
import cn.stylefeng.roses.kernel.oauth2.modular.service.LoginService;
import cn.stylefeng.roses.kernel.oauth2.modular.service.Oauth2UserInfoService;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OAuth统一回调地址
 *
 * @author fengshuonan
 * @date 2022/7/1 17:16
 */
@Controller
@ApiResource(name = "租户控制器")
@Slf4j
public class OAuthController {

    @Resource
    private LoginService loginService;

    @Resource
    private Oauth2UserInfoService oauth2Api;

    @Resource
    private OAuth2Config oAuth2Config;

    /**
     * 跳转到第三方平台进行Oauth2认证
     *
     * @author fengshuonan
     * @date 2022/7/1 17:15
     */
    @GetResource(name = "跳转到第三方平台进行Oauth2认证", path = "/oauth2/detection/{source}", requiredPermission = false, requiredLogin = false)
    public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
        AuthRequest authRequest = OAuthRequestFactory.getAuthRequest(source);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(authorizeUrl);
    }

    /**
     * 第三方登录成功后的回调地址
     *
     * @author fengshuonan
     * @date 2022/7/1 17:16
     */
    @GetResource(name = "第三方登录成功后的回调地址", path = "/oauth2/callback/{source}", requiredLogin = false, requiredPermission = false)
    public void callback(@PathVariable("source") String source, AuthCallback callback, HttpServletResponse response) throws IOException {

        // 通过回调的code，请求对应的oauth server获取用户基本信息和token
        AuthRequest authRequest = OAuthRequestFactory.getAuthRequest(source);
        AuthResponse<?> authResponse = authRequest.login(callback);

        AuthUser oauthUser = (AuthUser) authResponse.getData();
        log.info("第三方登录回调成功：" + oauthUser);

        // 进行第三方用户登录过程，获取本系统能识别的token
        String token = loginService.oauthLogin(oauthUser);

        //跳转到token登录接口
        response.sendRedirect(oAuth2Config.getFrontAppHost() + "/sso?from=oauth2&token=" + token);
    }

    /**
     * 第三方登录的头像
     *
     * @author fengshuonan
     * @date 2022/7/1 17:16
     */
    @GetResource(name = "第三方登录的头像", path = "/oauth2/avatar", requiredLogin = false, requiredPermission = false)
    public String avatar() {

        // 获取当前登录用户id
        Long userId = LoginContext.me().getLoginUser().getUserId();

        // 获取第三方登录用户的头像
        String avatarUrl = oauth2Api.getAvatarUrl(userId);

        return "redirect:" + avatarUrl;
    }

}
